#include "login.h"
#include "ui_login.h"
#include <QApplication>
#include <QFile>

Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    //只能输入数字
    ui->UserNameEdit->setValidator(new QIntValidator(ui->UserNameEdit));
    //改变图标
    setWindowIcon(QIcon(":/new/prefix1/FaceResources/logo.png"));
    //加载样式表
    QString styleSheetFile = ":/new/prefix2/StyleSheet/loginStyle.qss";
    QFile file(styleSheetFile);
    file.open(QFile::ReadOnly);
    if (file.isOpen())
    {
        QString styleSheet = this->styleSheet();
        styleSheet += QLatin1String(file.readAll());//读取样式表文件
        this->setStyleSheet(styleSheet);
        file.close();
    }
//    else
//    {
//        QMessageBox::information(this,"tip","cannot find qss file");
//    }
}

int Login::get_user_id()
{
    return user_id;
}

QString Login::get_listName()
{
    return listName;
}

Login::~Login()
{
    delete ui;
}

//登录
void Login::on_But_Login_clicked()
{
    if(ui->UserNameEdit->text().isEmpty() || ui->PassWordEdit->text().isEmpty())
    {
         QMessageBox::information(nullptr, "infor", "请填写完整！");
         ui->UserNameEdit->clear();
         ui->PassWordEdit->clear();
         //直接返回不继续执行
         return;
    }
    QString editPassword = ui->PassWordEdit->text();
    int editId = ui->UserNameEdit->text().toInt();

    QString md5_password = QCryptographicHash::hash(editPassword.toLatin1(),QCryptographicHash::Md5).toHex();

    QSqlQuery query;
    query.exec(QString("select * from users where id = %1;").arg(editId));
    //查库真实密码
    QString true_passWord;
    while(query.next())
    {
        true_passWord = query.value(1).toString();
    }
    //判断账号密码是否一致
//    qDebug() << "true:" << true_passWord << "\n edit:" << editPassword;
    if(true_passWord == md5_password)
    {
        user_id = editId;
        //创建对应用户的数据表
        listName = "list_" + QString::number(user_id);

        query.exec(QString("create table if not exists %1"
                           " (`name` text, start_time text,finish_time text, isFinish text not null default 'no',add_time text, introduction text)").arg(listName));

        emit LoginSuccess();
    }
    else
    {
        QMessageBox::information(nullptr, "infor", "用户名和密码不一致！");
//        ui->UserNameEdit->clear();
        ui->PassWordEdit->clear();
    }



}

void Login::on_But_Register_clicked()
{
    winRron = new Enroll();

    //设置注册窗口为模态
    winRron->setWindowModality(Qt::ApplicationModal);
    winRron->show();
}
